package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-13
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;


    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 微信小程序登录
     *
     * @param userLoginInfo
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginInfo) {
        // 1、调用微信后台接口，获取openId
        String openId = wechatService.getOpenId(userLoginInfo.getCode());

        // 2、根据openId查询数据库，判断用户是否已经存在（不存在就是新用户）
        FamilyMember familyMember = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();

        // 3、如果是新用户，构建用户对象（需要放入openId）
        if (ObjectUtil.isNull(familyMember)) {
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
        }

        // 4、调用微信后台接口，获取手机号
        String phoneNumber = wechatService.getPhoneNumber(userLoginInfo.getPhoneCode());

        // 5、新增或者修改用户信息（新增时需要生成用户昵称）
        saveOrUpdateFamilyMember(familyMember, phoneNumber);

        // 6、生成Token
        Map<String, Object> tokenMap = Map.of("userId",familyMember.getId(),"nickName", familyMember.getName());
        String token = tokenService.createToken(tokenMap);

        // 7、返回LoginVo
        return LoginVo.of(token, familyMember.getName());
    }

    private void saveOrUpdateFamilyMember(FamilyMember familyMember, String phoneNumber) {
        // 1、判断是否是新用户，如果老用户，修改
        if (ObjectUtil.isNotNull(familyMember.getId())) {
            // 判断用户手机号是否发生变化，如果发生变化，需要修改手机号
            if (!StrUtil.equals(familyMember.getPhone(), phoneNumber)) {
                familyMember.setPhone(phoneNumber);
                this.updateById(familyMember);
            }
            return;
        }
        // 2、如果是新用户，生成昵称，新增
        familyMember.setPhone(phoneNumber);
        /*int index = RandomUtil.randomInt(DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index);*/
        String nickName = RandomUtil.randomEle(DEFAULT_NICKNAME_PREFIX);

        familyMember.setName(nickName + phoneNumber.substring(7));
        this.save(familyMember);
    }
}
